package com.jarveis.frame.io;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.log4j.Logger;

import com.jarveis.frame.lang.CharacterUtil;
import com.jarveis.frame.util.Configuration;

/**
 * EMail发送类
 * 
 * @author liuguojun
 */
public class EmailSender {
	
	private static final Logger logger = Logger.getLogger(EmailSender.class);
	
	private String host; // Email的主机
	private String name; // Email的用户名
	private String pwd; // Email的密码
	private String from; // 发送Email
	private String to; // 发送信息到达的Email
	private String subject; // email主题
	private String msg; // email内容
	
	private static Configuration configuration = null;
	static {
		 configuration = new Configuration("config.properties");
	}
	
	public EmailSender(){
		this(configuration);
	}
	
	public EmailSender(Configuration config){
		this.host = config.get("mail.host");
		this.name = config.get("mail.username");
		this.pwd = config.get("mail.password");
		this.from = config.get("mail.from");
	} 

	public void setHost(final String host) {
		this.host = host;
	}

	public void setName(final String name) {
		this.name = name;
	}

	public void setPwd(final String pwd) {
		this.pwd = pwd;
	}

	public void setFrom(final String from) {
		this.from = from;
	}

	public void setTo(final String to) {
		this.to = to;
	}

	public void setSubject(final String subject) {
		this.subject = subject;
	}

	public void setMsg(final String msg) {
		this.msg = msg;
	}

	public void send(){
		final HtmlEmail mail = new HtmlEmail();
		mail.setSSL(false);
		mail.setHostName(host);
		mail.setAuthentication(name, pwd);
		mail.setSubject(subject);
		mail.setCharset(CharacterUtil.UTF8);
		try {
			mail.setFrom(from);
			mail.addTo(to);
			mail.setHtmlMsg(msg);
			mail.send();
		} catch (EmailException ex) {
			logger.error(ex.getMessage(), ex);
		}
		
	}

	public void send(String to, String subject, String msg) {
		this.to = to;
		this.subject = subject;
		this.msg = msg;
		send();
	}
}
